﻿namespace KeRui.Upload
{
    using System;
    using System.Runtime.CompilerServices;
    using System.Web;

    public class ProgressModule : IHttpModule
    {
        public event UpdateProgressHandler UpdateProgress;

        private void Application_BeginRequest(object src, EventArgs e)
        {
            Settings current = Settings.Current;
            if (current.Advanced.EnableProgressBar)
            {
                HttpApplication inApp = (HttpApplication) src;
                string inID = inApp.Request.QueryString[current.QueryFields.UploadID];
                string inDumpPath = inApp.Request.QueryString[current.QueryFields.DumpPath];
                if ((inID != null) || (inDumpPath != null))
                {
                    StateInfo inState = ProgressUtils.CreateState(inID);
                    this.DoUpdateProgress(inState.ID);
                    try
                    {
                        Registration.CheckValid();
                        KeRui.Upload.TempFile.SetTempPath(current.Advanced.TempDirectory, true);
                        ProgressUtils.DoUpload(this, inApp, inState, current, inDumpPath);
                    }
                    catch (Exception exception)
                    {
                        if (Settings.Current.Advanced.LogExceptions)
                        {
                            Log.ExceptionDetails(exception);
                        }
                        inState.Note = string.Format(current.Notes.Exception, exception.Message);
                        this.DoUpdateProgress(inState.ID);
                        if (exception is UnauthorizedAccessException)
                        {
                            throw exception;
                        }
                    }
                    finally
                    {
                        inState.Finished = true;
                    }
                }
            }
        }

        public void Dispose()
        {
        }

        internal void DoUpdateProgress(int inID)
        {
            if (!((this.UpdateProgress == null) || Registration.IsLite))
            {
                ProgressEventArgs e = new ProgressEventArgs();
                e.State = new Progress(inID);
                this.UpdateProgress(this, e);
            }
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(this.Application_BeginRequest);
        }

        public string ModuleName
        {
            get
            {
                return "ProgressModule";
            }
        }

        public delegate void UpdateProgressHandler(object source, EventArgs e);
    }
}

